import axios, { type AxiosResponse } from "axios"
import type { Response } from "@/type/all-type"
import router from "@/router/index"

const service = axios.create({
    baseURL: '/api',
    timeout: 100000
})


service.interceptors.request.use((config) => {
    //在请求之前做些什么(获取并设置token)
    // config.headers['token'] = getToken('token');
    return config
}, (error) => {
    return Promise.reject(error)
})

service.interceptors.response.use((response) => {
    const { code, msg } = response.data as Response;
    if (code === 102) {
        ElMessage.error(msg);
        setTimeout(function () {
            router.push('/login')
        }, 3000)
    } else if (code !== 200) {
        throw new Error(msg);
    }
    return response;
})

function request(url: string, data?: any): Promise<AxiosResponse<Response>> {
    return service({
        method: "POST",
        url,
        data
    })
}

export default request;
